<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Partner extends CI_Controller {

    function __construct(){
        parent::__construct();
        $this->load->model('partner/partner_model');
    }

    function index(){
        $result = $this->partner_model->get_many_by(array('delete_flag'=> UNDELETE_FLAG, 'draft' => 'no'));
        $data['result'] =  $result;
        $data['tpl'] = 'admin/partner/index';
        $this->load->view('layout/master', $data);
    }

    function add(){
        $this->_update();
    }

    function edit($id){
        $this->_update($id);
    }

    function _update($partner_id = 0){
        $partner_id = intval($partner_id);
        $info = array();

        if ($_POST){
            $post_id  = $this->input->post('partner_id');
            $openbeta = explode('/', trim($this->input->post('openbeta')));
            $info = array(
                'partner_id'           => $post_id,
                'title'                => $this->input->post('title'),
                'website'              => $this->input->post('website'),
                'comment'              => $this->input->post('comment'),
                'position'             => $this->input->post('position'),
                'update_date'          => date('Y-m-d H:i:s', time()),
                'draft'                => DRAFT_NO,
                'active_flag'          => ACTIVE_FLAG
            );

            if ($this->partner_model->update($post_id, $info)) {
                $data['msg'] = 'Đối tác đã được '. ($partner_id != 0 ? 'lưu' : 'thêm') .' thành công';
            }
        }

        /*Check draft*/
        if ($partner_id == 0){
            $check_draft = $this->partner_model->check_draft();
            if (is_bool($check_draft)){
                $partner_id = $this->partner_model->insert(array('draft' => 'yes', 'create_date' => date('Y-m-d H:i:s'), 'user_id' => $_SESSION['admin']['id']));
            } else {
                $data['data'] = $check_draft;
                $partner_id   = $check_draft['partner_id'];
            }
        }

        /*Info*/
        if (!isset($data['data'])){
            $data['data'] = $this->partner_model->as_array()->get_by(array('partner_id' => $partner_id));
        }

        $data['tpl'] = 'admin/partner/edit';
        $this->load->view('layout/master', $data);
    }
}